<?php
namespace app\api\controller\order;
use app\common\controller\BaseController;
use app\common\model\order\ShopOrderModel;
use app\common\model\setting\SettingStorePlatformModel;
use app\common\service\appeal\ShopOrderAppealService;
use app\common\service\order\ShopOrderCommentService;
use app\common\service\order\ShopOrderLogService;
use app\common\service\order\ShopOrderService;
use app\common\service\setting\SettingStorePlatformService;
use app\common\service\system\SettingService as SystemSettingService;
use app\common\service\webscoket\CacheRedisService;
use app\common\service\webscoket\LockService;
use app\common\validate\appeal\ShopOrderAppealValidate;
use app\common\validate\order\ShopOrderValidate;
use hg\apidoc\annotation as Apidoc;
/**
 * @Apidoc\Title("订单管理")
 * @Apidoc\Group("order")
 * @Apidoc\Sort("250")
 */
class ShopOrder extends BaseController
{
    /**
     * @Apidoc\Title("取消订单")
     * @Apidoc\Method("POST")
     * @Apidoc\Param(ref="app\common\model\order\ShopOrderModel", field="id")
     */
    public function cancelOrder()
    {
        $param = $this->params(['id/d' =>null]);
        $param['member_id'] =member_id(true);
        validate(ShopOrderValidate::class)->scene('cancelOrder')->check($param);
        $edit_data = [
            'pending_member_id'=>null,
            'pending_member_account_id'=>null,
            'pending_time'=>null,
        ];
        $where = [
            ['id','=',$param['id']],
            ['is_delete','=',0],
            ['pending_member_id','=',$param['member_id']],
            ['pending_time','>=',date('Y-m-d H:i:s')],
            ['status','in',[ShopOrderModel::getStatus('o_select',1),ShopOrderModel::getStatus('o_taking',1)]],
        ];
        $data = ShopOrderService::customEdit($where, $edit_data);
        if($data){
            //取消成功清空缓存
            CacheRedisService::delete('OrderAssignListener_'.$param['member_id']);
        }
        return success($data,'取消成功');
    }
    /**
     * @Apidoc\Title("确认订单")
     * @Apidoc\Method("POST")
     * @Apidoc\Param(ref="app\common\model\order\ShopOrderModel", field="id")
     */
    public function confirmOrder()
    {

        $param = $this->params(['id/d' =>null]);
        $param['member_id'] =member_id(true);
        validate(ShopOrderValidate::class)->scene('confirmOrder')->check($param);
        $where =[
            ['id','=',$param['id']],
            ['is_delete','=',0],
            ['pending_member_id','=',$param['member_id']],
            ['pending_member_account_id','<>','null'],
            ['pending_time','>=',date('Y-m-d H:i:s')],
            ['status','in',[ShopOrderModel::getStatus('o_select',1),ShopOrderModel::getStatus('o_taking',1)]]
        ];

        $list = ShopOrderService::getList($where,0,0,['pending_time'=>'asc'],'id,status,old_status,member_id,member_account_id,pending_member_id,pending_member_account_id,merchant_id');
        foreach ($list as $key=>$val){
            $edit_data = [
                'pending_member_id'=>null,
                'pending_member_account_id'=>null,
                'pending_time'=>null,
                'meet_time'=>date('Y-m-d H:i:s'),
                'status'=>ShopOrderModel::getStatus('o_operation',1),
                'old_status'=>$val['status'],
                'member_id'=>$val['pending_member_id'],
                'member_account_id'=>$val['pending_member_account_id'],
            ];
            $data = ShopOrderService::customEdit($where, $edit_data);
            if($data){
                $log_res = ShopOrderLogService::addByCode('MJJD',[
                    'merchant_id'=>$val['merchant_id'],
                    'shop_order_id'=>$val['id'],
                    'order_status'=>$edit_data['status'],
                    'create_uid'=>$param['member_id'],
                ]);
            }
        }
        //确认订单清空缓存
        CacheRedisService::delete('OrderAssignListener_'.$param['member_id']);
        if(count($list)<=0){
            return error('订单失效，接单失败');
        }
        return success([],'接单成功');
    }


    /**
     * @Apidoc\Title("查询订单状态")
     * @Apidoc\Method("POST")
     * @Apidoc\Param(ref="app\common\model\order\ShopOrderModel", field="id")
     */
    public function getOrderStatus()
    {
        return success(ShopOrderService::getOrderStatus(1));
    }
    /**
     * @Apidoc\Title("订单管理列表")
     * @Apidoc\Query(ref="pagingQuery")
     * @Apidoc\Query(ref="sortQuery")
     * @Apidoc\Query(ref="searchQuery")
     * @Apidoc\Query(ref="dateQuery")
     * @Apidoc\Returned(ref="expsReturn")
     * @Apidoc\Returned(ref="pagingReturn")
     * @Apidoc\Returned("list", type="array", desc="订单管理列表", children={
     *   @Apidoc\Returned(ref="app\common\model\order\ShopOrderModel", field="id,title,content,is_disable,create_time,update_time")
     * })
     */
    public function list()
    {
        $param = $this->params(['status/d' => 0]);
        $status = ShopOrderService::getOrderStatus(1);
        $status = $status['order_status'];
        $status_values = array_column($status,'value');
        $member_id = member_id(true);
        $where[] = ['member_id','=',$member_id];
        //默认第一个状态查询
        if($param['status']==0 && count($status_values)>0){
            $param['status'] = $status_values[0];
        }
        if(in_array($param['status'],$status_values) && $param['status']<=10){
            $where[] = ['status','=',$param['status']];
        }else if($param['status']>10){
            $status = 1;
            switch ($param['status']){
                case 11:
                    $status = 1;
                    break;
                case 12:
                    $status = 2;
                    break;
                case 13:
                    $status = 4;
                    break;
                case 14:
                    $status = 3;
                    break;
            }
            $comment_where[] = ['is_delete','=',0];
            $comment_where[] = ['comment_status','=',3];
            $comment_where[] = ['status','=',$status];
            $comment_where[] = ['member_id','=',$member_id];
            $order_ids = ShopOrderCommentService::getShopOrderIds($comment_where);
            if($order_ids){
                $where[] = ['id','in',$order_ids];
            }else{
                $where[] = ['id','=',0];
            }
        }
        //查询字段
        $field = 'a.id,a.status,a.principal,a.commission,a.advance_amount,a.order_on,a.ship_time,a.meet_time,a.shop_product_type_code,
            platform.image_id as platform_image_id,
            goods.image_id as goods_image_id,
            goods.order_price,
            shop.title as shop_title,
            type.title as type_title,
            enter.comment_type,
            refund.title as refund_title,
            account.accname
            ';
        $data = ShopOrderService::list($where, $this->page(), $this->limit(), $this->order(),$field,5);
        return success($data);
    }
    /**
     * @Apidoc\Title("订单管理信息")
     * @Apidoc\Query(ref="app\common\model\order\ShopOrderModel", field="id")
     * @Apidoc\Returned(ref="app\common\model\order\ShopOrderModel")
     */
    public function info()
    {
        $param = $this->params(['id/d' => '']);
        validate(ShopOrderValidate::class)->scene('info')->check($param);
        $where = [
            ['id','=',$param['id']],
            ['is_delete','=',0],
            ['member_id','=',member_id(true)]
        ];
        $field = 'platform.title as platform_title,
            platform.image_id as platform_image_id,
            type.title as type_title,
            shop.title as shop_title,
            refund.title as refund_title,
            goods.id as goods_id,
            goods.third_id as goods_third_id,
            goods.goods_title,
            goods.image_id as goods_image_id,
            goods.goods_spec,
            goods.goods_type,
            product.h_pay_time,
            product.money as product_money,
            product.c_sort_type,
            product.c_region_id,
            product.c_pay_num,
            product.c_start_price,
            product.c_end_price,
            product.remark as product_remark,
            product.remark_images,
            product.c_subject,
            enter.comment_type,
            enter.enter_type,
            enter.keyword as enter_keyword,
            enter.qr_image_id,
            enter.comment_image_id,
            enter.comment_vido_id,
            enter.content as enter_content,
            account.consignee as ac_consignee,
            account.phone as ac_phone,
            account.region_id as ac_region_id,
            account.address as ac_address,
            account.accname,
            a.*';
        $data = ShopOrderService::info($where,$field,true,true);
        //查询返款设置
        $setting = SystemSettingService::info('order_max_principal,order_actual_amount_differ');
        $data['order_max_principal'] = $setting['order_max_principal'];
        $data['order_actual_amount_differ'] = $setting['order_actual_amount_differ'];
        return success($data);
    }


    /**
     * @Apidoc\Title("订单提交")
     * @Apidoc\Method("POST")
     * @Apidoc\Param(ref="app\common\model\order\ShopOrderModel", field="id")
     */
    public function submitOrder()
    {
        $param = $this->params(['info' => null]);
        $data = ShopOrderService::submitOrder($param['info']);
        return success($data);
    }
    /**
     * @Apidoc\Title("订单截图提交")
     * @Apidoc\Method("POST")
     * @Apidoc\Param(ref="app\common\model\order\ShopOrderModel", field="id")
     */
    public function submitScreenshot()
    {
        $param = $this->params(['id/d' => null,'logistics_image_id/d'=>null,'evaluate_image_id/d'=>null]);
        validate(ShopOrderValidate::class)->scene('submitScreenshot')->check($param);
        $data = ShopOrderService::submitScreenshot($param['id'],$param);
        return success($data);
    }
    /**
     * @Apidoc\Title("接单后取消订单")
     * @Apidoc\Query(ref="app\common\model\order\ShopOrderModel", field="id")
     * @Apidoc\Returned(ref="app\common\model\order\ShopOrderModel")
     */
    public function cancelOrderByOperation()
    {
        $param = $this->params(['id/d' =>null]);
        $param['member_id'] =member_id(true);
        validate(ShopOrderValidate::class)->scene('cancelOrder')->check($param);
        $data = ShopOrderService::cancelOrderByOperation($param['id'],$param);
        return success($data);
    }

    /**
     * @Apidoc\Title("店铺或宝贝详情验证")
     * @Apidoc\Query(ref="app\common\model\order\ShopOrderModel", field="id")
     * @Apidoc\Returned(ref="app\common\model\order\ShopOrderModel")
     */
    public function answerVerify()
    {
        $param = $this->params(['id/d' =>null,'type/d'=>1,'answer/s'=>null]);
        $param['member_id'] =member_id(true);
        validate(ShopOrderValidate::class)->scene('cancelOrder')->check($param);
        $data = ShopOrderService::answerVerify($param['id'],$param);
        return success($data);
    }
    /**
     * @Apidoc\Title("订单申诉")
     * @Apidoc\Method("POST")
     * @Apidoc\Param(ref="app\common\model\order\ShopOrderModel", field="id,title,content,is_disable")
     */
    public function appeal()
    {
        $param = $this->params(ShopOrderAppealService::$edit_field);
        validate(ShopOrderAppealValidate::class)->scene('add')->check($param);
        $param['is_terminal'] = 2;
        $data = ShopOrderService::appeal($param['shop_order_id'], $param);
        return success($data);
    }
    /**
     * @Apidoc\Title("订单追评截图提交")
     * @Apidoc\Method("POST")
     * @Apidoc\Param(ref="app\common\model\order\ShopOrderModel", field="id")
     */
    public function submitCommentScreenshot()
    {
        $param = $this->params(['id/d' => null,'order_comment_id/d'=>null,'evaluate_image_id/d'=>null]);
        validate(ShopOrderValidate::class)->scene('submitCommentScreenshot')->check($param);
        $data = ShopOrderService::submitCommentScreenshot($param['id'],$param);
        return success($data);
    }

    /**
     * 平台补贴商品抢购订单
     * @Author: 易军辉
     * @DateTime:2024-10-22 15:39
     * @return \json
     */
    public function allocationOrder()
    {
        $param = $this->params(['shop_product_id/d' =>null]);
        $param['member_id'] =member_id(true);
        validate(ShopOrderValidate::class)->scene('allocationOrder')->check($param);
        // 获取 Redis 分布式锁服务类
        $lockService = app()->make(LockService::class);

        // 设置锁的唯一键，使用商品ID作为标识
        $lockKey = 'shop_product_' . $param['shop_product_id'];

        // 执行锁定操作，避免超卖
        $data = $lockService->exec($lockKey, function () use ($param) {
            // 抢购订单逻辑，调用业务服务类处理具体的下单流程
            return ShopOrderService::allocationOrder($param['shop_product_id'], $param);
        });

        // 返回结果
        return success($data);
    }
    /**
     * @Apidoc\Title("平台补贴商品抢购订单详情")
     * @Apidoc\Query(ref="app\common\model\order\ShopOrderModel", field="id")
     * @Apidoc\Returned(ref="app\common\model\order\ShopOrderModel")
     */
    public function allocationInfo()
    {
        $param = $this->params(['id/d' => '']);
        validate(ShopOrderValidate::class)->scene('info')->check($param);
        $where = [
            ['id','=',$param['id']],
            ['is_delete','=',0],
            ['member_id','=',member_id(true)]
        ];
        $field = '
            a.id,
            a.shop_product_id,
            a.shop_product_price_ids,
            a.setting_price_range_ids,
            a.merchant_id,
            a.merchant_shop_id,
            a.member_id,
            a.member_account_id,
            a.principal,
            a.commission,
            a.actual_amount,
            a.advance_amount,
            a.status,
            a.shop_product_type_code,
            shop.title as mer_shop_title,
            platform.title as platform_title,
            platform.code as platform_code,
            platform.image_id as platform_image_id,
            enter.enter_type,
            enter.keyword as enter_keyword,
            enter.qr_image_id,
            product.remark as product_remark,
            product.remark_images,
            product.c_subject';
        $data = ShopOrderService::info($where,$field,true,true);

        /*****************商品名称处理*************************/
        if(isset($data['goods_list'])){
            foreach ($data['goods_list'] as $key=>$val){
                $options = $this->generateOptions($val['goods_title']);
                $data['goods_list'][$key]['options'] = $options;
                $data['goods_list'][$key]['goods_title'] = mb_substr($val['goods_title'], 0, 1, 'UTF-8');
                if($key==0){
                    $data['advance_amount'] = $val['order_price'];
                }
            }
        }
        /*****************店铺名称处理*************************/
        if(isset($data['mer_shop_title'])){
            $options = $this->generateOptions($data['mer_shop_title']);
            $data['mer_shop_options']= $options;
            $data['mer_shop_title']=mb_substr($data['mer_shop_title'], 0, 1, 'UTF-8');
        }
        //查询返款设置
        $setting = SystemSettingService::info('order_max_principal,order_actual_amount_differ');
        $data['order_max_principal'] = $setting['order_max_principal'];
        $data['order_actual_amount_differ'] = $setting['order_actual_amount_differ'];
        return success($data);
    }


    /**
     * @Apidoc\Title("名称处理")
     * @Apidoc\Query(ref="app\common\model\order\ShopOrderModel", field="id")
     * @Apidoc\Returned(ref="app\common\model\order\ShopOrderModel")
     */
    private function generateOptions($productName)
    {
        // 获取商品名称的第一个字
        $firstChar = mb_substr($productName, 0, 1, 'UTF-8');

        // 获取商品名称的总长度
        $nameLength = mb_strlen($productName, 'UTF-8');

        // 初始化选项数组，首先放入第一个字
        $options = [$firstChar];

        // 如果商品名称有多于一个字，生成其他干扰项
        if ($nameLength > 1) {
            // 获取第一个字之后的所有字
            $remainingChars = [];
            for ($i = 1; $i < $nameLength; $i++) {
                $char = mb_substr($productName, $i, 1, 'UTF-8');
                // 确保没有重复字
                if (!in_array($char, $options)) {
                    $remainingChars[] = $char;
                }
            }
            $remainingChars = array_unique($remainingChars);
            // 随机打乱剩余的字
            shuffle($remainingChars);

            // 从剩余的字中取最多3个，确保总选项数不超过4个
            $remainingCount = min(3, count($remainingChars));
            $options = array_merge(array_slice($remainingChars, 0, $remainingCount),$options);
            shuffle($options);
        }

        // 最后打乱整个选项数组，确保第一个字的位置随机
        shuffle($options);

        // 返回最终的选项
        return $options;
    }


    /**
     * @Apidoc\Title("查询抢单列表参数")
     * @Apidoc\Query(ref="app\common\model\order\ShopOrderModel", field="id")
     * @Apidoc\Returned(ref="app\common\model\order\ShopOrderModel")
     */
    public function getGrabParams()
    {
        $where = $this->where(where_delete());
        $where[] = ['is_disable','=',0];

        $platform_list= SettingStorePlatformService::list($where,0,0, $this->order(),'id as value,title as label,code,is_disable as disable');
        foreach ($platform_list as $key=>$val){
            if($val['code'] == SettingStorePlatformModel::CODE_TM){
                unset($platform_list[$key]);
            }
        }
        array_unshift($platform_list, ['value' =>0, 'label' => '全部','code' => 'all']);
        $data['platform_list'] = $platform_list;
        return success($data);
    }

    /**
     * @Apidoc\Title("查询抢单列表")
     * @Apidoc\Query(ref="app\common\model\order\ShopOrderModel", field="id")
     * @Apidoc\Returned(ref="app\common\model\order\ShopOrderModel")
     */
    public function getGrabList()
    {
        $param = $this->params([
            'store_platform_id/d' => null,
            'member_account_id/d' => null,
        ]);
        $param['member_id'] = member_id();
        $data = ShopOrderService::getGrabList($param, $this->page(), $this->limit(), $this->order());
        return success($data);
    }
    /**
     * @Apidoc\Title("抢单")
     * @Apidoc\Query(ref="app\common\model\order\ShopOrderModel", field="id")
     * @Apidoc\Returned(ref="app\common\model\order\ShopOrderModel")
     */
    public function grabOrder()
    {
        $param = $this->params([
            'member_account_id/d' =>null,
            'shop_order_id/d'=>null
        ]);
        $param['member_id'] =member_id(true);
        validate(ShopOrderValidate::class)->scene('grabOrder')->check($param);
        // 获取 Redis 分布式锁服务类
        $lockService = app()->make(LockService::class);

        // 设置锁的唯一键，使用商品ID作为标识
        $lockKey = 'grab_order_id' . $param['shop_order_id'];

        // 执行锁定操作，避免超卖
        $data = $lockService->exec($lockKey, function () use ($param) {
            // 抢购订单逻辑，调用业务服务类处理具体的下单流程
            return ShopOrderService::grabOrder($param['shop_order_id'], $param);
        });
        // 返回结果
        return success($data);
    }
}
